var express = require('express');
var router = express.Router();

var {
  Users
} = require("../utils/model")
var {
  startEncrypt,
  getDecrypt,
  checkSession
} = require("../utils")

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

// 注册

router.post("/register", (req, res) => {
  var body = req.body;
  console.log(body);
  var {
    username,
    password
  } = body;
  if (username && password) {
    Users.findOne({
      username: username
    }).then(result => {
      if (result) {
        res.send("<script>alert('用户名已存在');location.href='/register'</script>")
      } else {
        body.time = new Date();
        Users.insertMany(body)
          .then(data => {
            res.send(`<script>alert('注册成功,正在跳转登录页面');location.href='/login?username=${startEncrypt(username)}'</script>`)
          })
      }
    })
  } else {
    res.send("<script>alert('请填写用户名和密码');location.href='/register'</script>")
  }
})

router.post("/login", (req, res) => {
  var body = req.body;
  console.log(body);
  if (body.username && body.password) {
    Users.findOne({
      username: body.username
    }).then(result => {
      if (result) {
        if (result.password === body.password) {
          req.session.username = result.username;
          req.session.logintime = new Date();
          req.session.token = startEncrypt(result.username); // 判断用户是否登录 
          res.redirect("/"); // 登录成功 跳转首页 重定向  
        } else {
          res.send("<script>alert('用户名或者密码错误');location.href='/login'</script>")
        }
      } else {
        res.send("<script>alert('用户名或者密码错误');location.href='/login'</script>")
      }
    })
  } else {
    res.send("<script>alert('请填写用户名、密码');location.href='/login'</script>")
  }
})

router.post("/changepass", (req, res) => {
  checkSession(req, res, () => {
    var body = req.body;
    console.log(body);
    Users.findOne({
      username: body.username,
    }).then(data => {
      if (data) {
        if (data.password == body.oldpass) {
          Users.updateMany({
            username: body.username,
          }, {
            $set: {
              password: body.newpass
            }
          }).then(result => {
            res.json({
              code: 200,
              type: 1,
              msg: "密码修改成功....."
            })
          })
        } else {
          res.json({
            code: 200,
            type: 0,
            msg: "旧密码不正确....."
          })
        }
      } else {
        res.json({
          code: 200,
          type: 0,
          msg: "用户名不存在....."
        })
      }
    })
  })
})

router.all("/some", (req, res) => {
  res.json({
    code: 200,
    msg: "操作成功"
  })
})



module.exports = router;